package com.biz.service.auth.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.biz.dao.user.UserDAO;
import com.biz.dto.user.RoleDTO;
import com.biz.dto.user.UserDTO;

public class UserDetailServiceImpl implements UserDetailsService{
	@Resource(name="userDAOImpl")
	private UserDAO userDAO;
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserDTO user = userDAO.query(UserDTO.class, username);
		if (user == null) {
			throw new UsernameNotFoundException(username);
		}
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user.getUsername());
		user.setAuthorities(grantedAuths);
		return user; 
	}
	protected Set<GrantedAuthority> obtionGrantedAuthorities(String username) {
		List<RoleDTO> list = userDAO.queryRoleByUser(username); 
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		if(list!=null && list.size()>0){
			for(RoleDTO li:list){
				authSet.add(new SimpleGrantedAuthority(String.valueOf(li.getRoleId())));
			}
		}
		return authSet;
	}
}
